package com.bi.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.bi.common.ErrorCode;
import com.bi.exception.BusineseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ExcelUtils {
    /**
     * excel 转 csv
     *
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        CommonUtils.checkNullParams(multipartFile);
        try {
            // 读取数据
            List<Map<Integer, String>> list = null;
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
            StringBuilder resStr = new StringBuilder();
            for (int i = 1; i < list.size(); i++) {
                List<String> tpStrList = list.get(i).values().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
                resStr.append(StringUtils.join(tpStrList, ",")).append("\n");
            }
            return resStr.toString();
        } catch (Exception e) {
            throw new BusineseException(ErrorCode.SYSTEM_ERROR, "读取表格数据失败");
        }
    }

    public static String excelToCsv() {
        try {
            File file = ResourceUtils.getFile("classpath:bi测试表.xlsx");
            // 读取数据
            List<Map<Integer, String>> list = null;
            list = EasyExcel.read(file)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
            StringBuilder resStr = new StringBuilder();
            for (int i = 1; i < list.size(); i++) {
                List<String> tpStrList = list.get(i).values().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
                resStr.append(StringUtils.join(tpStrList, ",")).append("\n");
            }
            return resStr.toString();
        } catch (Exception e) {
            throw new BusineseException(ErrorCode.SYSTEM_ERROR, "读取表格数据失败");
        }
    }

    public static void main(String[] args) {
        excelToCsv(null);
    }
}